import React, {useState} from 'react';
import './css/Navbar.css';
import {useDispatch, useSelector} from "react-redux";
import {Avatar, Card, Input, message, notification} from "antd";
import {EditOutlined, EllipsisOutlined, RollbackOutlined, SettingOutlined, UserOutlined} from "@ant-design/icons";
import Meta from "antd/lib/card/Meta";
import axios from "axios";
import {setUser} from "../store/modules/userStore";
import {Content} from "../utils/Content";
import {deleteCookie} from "../utils/cookieUtil";

const Navbar = ({activeComponent, setActiveComponent}) => {
    const [showAvatarCard, setShowAvatarCard] = useState(false);
    const [isEditingName, setIsEditingName] = useState(false);
    const [api, contextHolder] = notification.useNotification();
    const user = useSelector((state) => state.user.user);
    const dispatch = useDispatch();
    // 定义按钮点击事件
    const handleButtonClick = (componentName) => {
        setActiveComponent(componentName);
    };

    const handleAvatarClick = () => {
        setShowAvatarCard(true);
    };

    // 个人信息卡片的开启和关闭
    let timer;
    const handleMouseOver = () => {
        if (timer) {
            clearTimeout(timer);
        }
    };
    const handleMouseOut = () => {
        timer = setTimeout(() => {
            setShowAvatarCard(false);
            setIsEditingName(false);
        }, 1500);
    };

    // 改名机能
    const onEnterPress = (e) => {
        let name = e.target.value;
        if (name === '' || name.trim().length !== name.length) {
            message.error('用户名不能为空，不能含有空格');
            return;
        }
        if (name === user.name) {
            setIsEditingName(false);
            return;
        }
        axios.post(
            'http://localhost:5532/user',
            {
                id: user.id,
                name: name,
            }
        ).then(res => {
            if (res.data.code === 1) {
                message.success('修改成功');
            }else {
                return Promise.reject()
            }
        }).then(() => {
            axios.get(
                'http://localhost:5532/user/getById?id='+user.id,
            ).then(res => {
                if (res.data.code === 1){
                    dispatch(setUser(res.data.data));
                }
            });
        })
        setIsEditingName(false);
    };

    return (
        <div className="navbar">
            <img src={process.env.PUBLIC_URL + '/img/logo.png'} alt="Logo" id={'logo'}/>
            <div className="navbar-buttons">
                {/* 按钮列表 */}
                <button className={activeComponent === '主页' ? 'active' : ''}
                        onClick={() => handleButtonClick('主页')}>主页
                </button>
                <button className={activeComponent === '预约项目' ? 'active' : ''}
                        onClick={() => handleButtonClick('预约项目')}>预约项目
                </button>
                <button className={activeComponent === '历史订单' ? 'active' : ''}
                        onClick={() => handleButtonClick('我的订单')}>我的订单
                </button>
            </div>
            <div className="user-profile"
                 onClick={() => handleAvatarClick()}>
                {/* 用户头像和名称 */}
                <Avatar
                    style={{
                        backgroundColor: '#87d068',
                    }}
                    src={Content.DEFAULT_AVATAR}
                />
                <span className="username">{user.name}</span>
                {contextHolder}
                <div className={'dropdown-content'}>
                    {showAvatarCard && (
                        <Card
                            className={'avatar-card'}
                            onMouseOver={() => handleMouseOver()}
                            onMouseOut={() => handleMouseOut()}
                            style={{
                                width: 300,
                            }}
                            cover={
                                <img
                                    alt="example"
                                    src={process.env.PUBLIC_URL + "/img/metaCard.png"}
                                />
                            }
                            actions={[
                                <EditOutlined key="edit" onClick={() => setIsEditingName(!isEditingName)}/>,
                                // 退出登录按钮
                                <RollbackOutlined
                                    key="logout"
                                    onClick={() => {
                                        deleteCookie('auth')
                                        window.location.reload();
                                    }}
                                />
                            ]}
                        >
                            <Meta
                                avatar={<Avatar src={Content.DEFAULT_AVATAR}/>}
                                title={
                                    isEditingName ?
                                        <Input
                                            placeholder={user.name}
                                            onPressEnter={onEnterPress}
                                            rootClassName={'EditNameInput'}
                                        />
                                        :
                                        user.name
                                }
                                description={user.phone}
                            />
                        </Card>
                    )}
                </div>
            </div>
        </div>
    );
};

export default Navbar;
